require 'MVVM.Sources.Infrastructure.ViewModelBase'
require 'MVVM.Sources.Infrastructure.BindableProperty'
require 'MVVM.Sources.Infrastructure.CompoundBindableProperty'
require 'Net.SendAndWaitRequest'

LoginViewModel = class('LoginViewModel', ViewModelBase)

function LoginViewModel:ctor()
    self.Username = BindableProperty.new('test')
    self.Password = BindableProperty.new('1')

    self.OnClickRegister = {
        OnClick = function()
            coroutine.start(function()
                local reqMsg = Login.RegisterReq()
                reqMsg.username = self.Username.Value
                reqMsg.password = self.Password.Value

                local request = SendAndWaitRequest.new(MsgType.REGISTER, reqMsg:SerializeToString())
                request:SendAsync()

                if request.errorCode == 0 then
                    print('#############REGISTER SUCCESS#############')
                else
                    print('#############REGISTER FAILED#############')
                end
            end)
        end
    }

    self.OnClickLogin = {
        OnClick = function()
            coroutine.start(function()
                local reqMsg = Login.LoginReq()
                reqMsg.username = self.Username.Value
                reqMsg.password = self.Password.Value

                local request = SendAndWaitRequest.new(MsgType.LOGIN, reqMsg:SerializeToString())
                request:SendAsync()

                if request.errorCode == 0 then
                    local msg = Login.LoginResp()
                    msg:ParseFromString(request.response)
                    local playerId = msg.playerId
                    local conv = msg.conv
                    config.GAME_KCP_CONV = conv
                    MyPlayerId = playerId
                    gameMgr:ChangeState('ProcGame', nil)
                    print('#############LOGIN SUCCESS#############')
                else
                    print('#############LOGIN FAILED#############')
                end
            end)
        end
    }
end

LoginViewModelInstance = LoginViewModel.new()